<template>
  <div>
    <!-- 头部导航 -->
    <Nav>
      <el-breadcrumb-item
        slot="nav"
        v-for="(item,index) in breadcrumbList"
        :key="index"
        :to="{ path : item.href}"
      >{{item.name}}</el-breadcrumb-item>
    </Nav>
    <!-- 卡片内容区域 -->
    <el-card>
      <!-- 头部提示 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning" show-icon></el-alert>
      <!-- 商品分类选择 -->
      <el-row>
        选择商品分类：
        <el-cascader
          v-model="value"
          :options="paramsList"
          expand-trigger="hover"
          :props="cascaderProps"
          @change="handleChange"
        ></el-cascader>
      </el-row>
      <!-- 标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="idBtnDisable" @click="addParamsBtn">添加参数</el-button>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="idBtnDisable" @click="addParamsBtn">添加属性</el-button>
        </el-tab-pane>
      </el-tabs>
      <!-- 表格 -->
      <el-table :data="paramsTabeList" style="width: 100%" border>
        <!-- 展开行 -->
        <el-table-column width="80" type="expand">
          <template slot-scope="scope">
            <el-tag
              closable
              v-for="(item,index) in scope.row.attr_vals"
              :key="index"
              @close="handleColse(index,scope.row)"
            >{{item}}</el-tag>
            <!-- 文本框和按钮的切换 -->
            <el-input
              class="input-new-tag"
              v-if="scope.row.inputVisible"
              v-model="scope.row.inputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm(scope.row)"
              @blur="handleInputConfirm(scope.row)"
            ></el-input>
            <el-button
              v-else
              class="button-new-tag"
              size="small"
              @click="showInput(scope.row)"
            >+ New Tag</el-button>
          </template>
        </el-table-column>
        <!-- 序号行 -->
        <el-table-column label="#" type="index" width="80"></el-table-column>
        <el-table-column prop="attr_name" label="参数名称"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editDialog(scope.row.attr_id)"
            >修改</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="del(scope.row.attr_id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 点击添加参数对话框 -->
      <el-dialog
        :title="'添加'+ cateTitle"
        :visible.sync="addParamsDialogVisible"
        width="50%"
        @close="closeParams"
      >
        <el-form
          :model="addParamsForm"
          :rules="addParamsRules"
          ref="addParamsFormRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="动态参数" prop="attr_name">
            <el-input v-model="addParamsForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addParamsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addList">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 点击修改对话框 -->
      <el-dialog
        :title="'添加'+ cateTitle"
        :visible.sync="editParamsDialogVisible"
        width="50%"
        @close="editClose"
      >
        <el-form
          :model="editParamsForm"
          :rules="editParamsRules"
          ref="editParamsFormRef"
          label-width="100px"
        >
          <el-form-item label="动态参数" prop="attr_name">
            <el-input v-model="editParamsForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editParamsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmEdit">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import Nav from '../nav'
export default {
  data() {
    return {
      breadcrumbList: [
        {
          name: '首页',
          href: '/welcome',
        },
        {
          name: '商品管理',
        },
        {
          name: '参数列表',
        },
      ],
      // 商品列表分类数据
      paramsList: [],
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      value: [],
      //   标签页
      activeName: 'many',
      //   表格数据
      paramsTabeList: [],
      //   添加参数对话框
      addParamsDialogVisible: false,
      //   添加动态参数
      addParamsForm: {
        attr_name: '',
      },
      //   添加动态参数规则
      addParamsRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
      //   点击修改对话框
      editParamsDialogVisible: false,
      editParamsForm: {
        attr_name: '',
      },
      //   修改对话框的验证规则
      editParamsRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
    }
  },
  methods: {
    //   获取商品列表分类数据
    async getParamsList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200)
        return this.$message.error('获取商品分类列表数据失败')
      this.paramsList = res.data
    },

    // 监听选择商品分类的改变事件
    handleChange() {
      this.getParams()
    },
    // 标签页
    handleClick() {
      this.getParams()
    },

    // 获取参数数据
    async getParams() {
      const { data: res } = await this.$http.get(
        `categories/${this.getCascaderID}/attributes`,
        {
          params: { sel: this.activeName },
        }
      )
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      //   把attr_vals分割成数组
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 文本框的显示与隐藏
        item.inputVisible = false
        // 文本框输入的内容
        item.inputValue = ''
      })
      this.paramsTabeList = res.data
    },

    // 监听按钮添加参数对话框
    addParamsBtn() {
      this.addParamsDialogVisible = true
    },

    // 监听按钮添加参数对话框对话框关闭
    closeParams() {
      this.$refs.addParamsFormRef.resetFields()
    },

    // 点击确定添加表单数据
    addList() {
      this.$refs.addParamsFormRef.validate(async (valid) => {
        if (!valid) return
        const {
          data: res,
        } = await this.$http.post(
          `categories/${this.getCascaderID}/attributes`,
          { attr_name: this.addParamsForm.attr_name, attr_sel: this.activeName }
        )
        if (res.meta.status !== 201) return this.$message.error('添加数据失败')
        this.getParams()
        this.$message.success('添加数据成功')
        this.addParamsDialogVisible = false
      })
    },

    // 点击修改按钮对话框
    async editDialog(id) {
      const { data: res } = await this.$http.get(
        `categories/${this.getCascaderID}/attributes/${id}`,
        {
          attr_name: this.editParamsForm.attr_name,
          attr_sel: this.activeName,
        }
      )
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.$message.success('获取成功')
      this.editParamsForm = res.data
      this.editParamsDialogVisible = true
    },
    // 点击修改对话框关闭
    editClose() {
      this.$refs.editParamsFormRef.resetFields()
    },

    // 点击确认修改按钮
    confirmEdit(id) {
      this.$refs.editParamsFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.getCascaderID}/attributes/${this.editParamsForm.attr_id}`,
          {
            attr_name: this.editParamsForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.$message.success('修改成功')
        this.getParams()
        this.editParamsDialogVisible = false
      })
    },
    // 点击删除操作
    async del(id) {
      const { data: res } = await this.$http.delete(
        `categories/${this.getCascaderID}/attributes/${id}`
      )
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      this.getParams()
    },

    // 文本框的事件
    async handleInputConfirm(row) {
      // 处理文本框如果没有输入内容失去焦点，就会切换成按钮
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      //   否则就把内容添加到数据中
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      //   发起网络请求保存到数据库中
      this.saveAttrVals(row)
    },
    // 对attr_vals的操作保存到数据库
    async saveAttrVals(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.getCascaderID}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' '),
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('添加失败')
      }
      this.$message.success('修改数据成功')
    },
    // 删除对应的参数可选项
    handleColse(index, row) {
      row.attr_vals.splice(index, 1)
      this.saveAttrVals(row)
    },
    // 按钮的切换事件
    showInput(row) {
      row.inputVisible = true
      //   实现文本框自动获取焦点
      // $nextTick页面刷新之后执行里边的代码
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
  },
  created() {
    this.getParamsList()
  },
  components:{
    Nav
  },
  computed: {
    //   分类参数标签页下的按钮是否被禁用
    // 如果级联选择器的value值长度是3，则被选中，返回false
    // 否则返回true
    idBtnDisable() {
      if (this.value.length !== 3) return true
      return false
    },

    // 获取级联选择器中的选中id
    getCascaderID() {
      if (this.value.length === 3) {
        return this.value[2]
      }
      return null
    },

    // 动态计算对话框的title
    cateTitle() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    },
  },
}
</script>

<style >
.el-row {
  margin-top: 20px;
}

.el-tag {
  margin-right: 10px;
}
.input-new-tag {
  width: 150px;
}
</style>